package com.ease.map {
    import com.ease.map.common.enum.HandlerEnum;
    import com.ease.map.common.enum.LayerTypeEnum;
    import com.ease.map.common.util.GlowTween;
    import com.ease.map.common.util.ResourceUtil;
    import com.ease.map.constant.StringConstants;
    import com.ease.map.control.Blackboard;
    import com.ease.map.control.MousePosition;
    import com.ease.map.control.PanZoomBar;
    import com.ease.map.control.ScaleLine;
    import com.ease.map.control.WaitingMark;
    import com.ease.map.events.FeatureEvent;
    import com.ease.map.feature.Feature;
    import com.ease.map.geometry.basetype.Extent;
    import com.ease.map.geometry.basetype.Location;
    import com.ease.map.handler.IHandler;
    import com.ease.map.handler.feature.FeatureClickHandler;
    import com.ease.map.handler.feature.SelectFeaturesHandler;
    import com.ease.map.handler.feature.draw.DrawLineHandler;
    import com.ease.map.handler.feature.draw.DrawPointHandler;
    import com.ease.map.handler.feature.draw.DrawPolygonHandler;
    import com.ease.map.handler.feature.draw.EditLineHandler;
    import com.ease.map.handler.feature.draw.EditPointHandler;
    import com.ease.map.handler.feature.draw.EditPolygonHandler;
    import com.ease.map.handler.mouse.ClickHandler;
    import com.ease.map.handler.mouse.DragHandler;
    import com.ease.map.handler.mouse.WheelHandler;
    import com.ease.map.layer.FeatureLayer;
    import com.ease.map.layer.LayerData;
    import com.ease.map.task.query.LayerObjectIdQuery;
    import com.ease.map.task.query.LayerObjectIdsQuery;
    import com.kgis.widgets.managers.ErrorManager;

    import flash.text.TextFormat;

    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import com.ease.map.Map;

    /**
     * Map支撑类
     * 对地图的一些基础操作
     */
    [ExcludeClass]
    public class MapSupport {
        [ResourceBundle("MapCore")]
        private var _map:Map = null;

        public function MapSupport(vmap:Map) {
            this._map = vmap;
            this.addDefaultControls();
            this.addDefaultHandlers();
        }

        //
        public function get map():Map {
            return _map;
        }

        public function set map(value:Map):void {
            _map = value;
        }

        public function addDefaultControls():void {
            var panbar:PanZoomBar = new PanZoomBar();
            panbar.name = "panbar";
            panbar.x = 10;
            panbar.y = 10;
            this.map.addControl(panbar);

            var scaleLine:ScaleLine = new ScaleLine();
            scaleLine.name = "scaleLine";
            scaleLine.x = 10;
            scaleLine.y = this.map.size.h - 80;
            this.map.addControl(scaleLine);

            var msLabel:MousePosition = new MousePosition();
            msLabel.name = "xy"
            msLabel.x = this.map.size.w - 250;
            msLabel.y = this.map.size.h - 20;
            msLabel.prefix = ResourceUtil.getString(StringConstants.MAPSUPPORT_MOUSE_LOCATION)
            this.map.addControl(msLabel);

            var blackBoard:Blackboard = new Blackboard();
            blackBoard.name = "blackBoard";
            var blackboardFormat:TextFormat = new TextFormat();
            blackboardFormat.size = 12;
            blackboardFormat.color = 0x000000;
            blackboardFormat.font = "微软雅黑";
            blackBoard.labelFormat = blackboardFormat;
            blackBoard.x = 200;
            blackBoard.y = this.map.size.h - 30;
            this.map.addControl(blackBoard);

            var copyright:Blackboard = new Blackboard();
            copyright.name = "copyright";
            var labelCopyrightFormat:TextFormat = new TextFormat();
            labelCopyrightFormat.size = 10;
            labelCopyrightFormat.color = 0x666666;
            labelCopyrightFormat.font = "微软雅黑";
            copyright.labelFormat = labelCopyrightFormat;

            copyright.x = 15;
            copyright.y = this.map.size.h - 18;
            copyright.setInfo("kgis @copyright 2011");
            copyright.visible = true;

            this.map.addControl(copyright);

            var waitingMark:WaitingMark = new WaitingMark();
            waitingMark.name = "waitingMark";
            waitingMark.x = this.map.size.w / 2;
            waitingMark.y = this.map.size.h / 2;
            this.map.addControl(waitingMark);

        }

        public function refreshDefaultControls():void {
            //根据map的size刷新controls的位置
            var scaleLine:ScaleLine = this.map.getControlByName("scaleLine") as ScaleLine;
            scaleLine.y = this.map.size.h - 80;

            var msLabel:MousePosition = this.map.getControlByName("xy") as MousePosition;
            msLabel.x = this.map.size.w - 250;
            msLabel.y = this.map.size.h - 20;

            var blackBoard:Blackboard = this.map.getControlByName("blackBoard") as Blackboard;
            blackBoard.y = this.map.size.h - 30;

            var copyright:Blackboard = this.map.getControlByName("copyright") as Blackboard;
            copyright.y = this.map.size.h - 18;

            var waitingMark:WaitingMark = this.map.getControlByName("waitingMark") as WaitingMark;
            waitingMark.x = this.map.size.w / 2;
            waitingMark.y = this.map.size.h / 2;
        }

        private function addDefaultHandlers():void {
            var handler:IHandler = new DragHandler(this.map, HandlerEnum.DRAG_HANDLER);
            handler = new ClickHandler(this.map, HandlerEnum.CLICK_HANDLER);
            handler = new WheelHandler(this.map, HandlerEnum.WHEEL_HANDLER);
            handler = new FeatureClickHandler(this.map, HandlerEnum.FEATURE_CLICK_HANDLER);
            handler = new SelectFeaturesHandler(this.map, HandlerEnum.SELECT_FEATURES_HANDLER);
            handler = new DrawLineHandler(this.map, HandlerEnum.DRAW_LINE_HANDLER);
            handler = new DrawPointHandler(this.map, HandlerEnum.DRAW_POINT_HANDLER);
            handler = new DrawPolygonHandler(this.map, HandlerEnum.DRAW_POLYGON_HANDLER);
            handler = new EditPointHandler(this.map, HandlerEnum.EDIT_POINT_HANDLER);
            handler = new EditLineHandler(this.map, HandlerEnum.EDIT_LINE_HANDLER);
            handler = new EditPolygonHandler(this.map, HandlerEnum.EDIT_POLYGON_HANDLER);
        }

        /**
         * 定位指定的feature(地图上存在)
         * @param feature 需要定位的对象
         * @param centered 是否居中显示
         * @param appendmode 是否追加模式，true:不清除掉原来的高亮设施
         */
        public function LocateFeature(feature:Feature, zoomlevel:Number = 12, centered:Boolean = true, appendmode:Boolean = false, spec:Object = null):void {
            if (!feature) {
                return;
            }
            var loc:Location = feature.getLocation();
            if (!appendmode) {
                //清除已有选中的设施
                this.map.clearSelection();
            }
            feature.selected = true;
            feature.executeDrawing();

            //闪烁50*50毫秒结束
            new GlowTween(feature, 50, 0x00ff00, 0, 5);

            //发出选中设施事件
            var fevt:FeatureEvent = new FeatureEvent(FeatureEvent.FEATURE_SELECTED, feature);
            fevt.spec = spec;
            this.map.dispatchEvent(fevt);

            if (centered) //居中
            {
                this.map.moveTo(loc, zoomlevel);
            }
        }

        /**
         * 定位指定图层中的指定objectid的图形
         * @param layerid 图层id
         * @param objectid 对象的id
         * @param highlightmode  结果集的显示方式
         * @param centered 是否居中显示
         * @param appendmode 是否追加模式，true:不清除掉原来的高亮设施
         */
        public function QueryAndLocateFeatureById(layerid:Number, objectid:Number, zoomlevel:Number = 14, centered:Boolean = true, appendmode:Boolean = false, spec:Object = null):void {
            //先在当前地图窗口上查询
            var findedLayer:Boolean = false;

            var layer:FeatureLayer = map.getLayerById(layerid) as FeatureLayer;
            if (!layer) {
                trace("没有取到layerid对应的图层");
                return;
            }
            if (zoomlevel == 0) {
                //取当前图层符号的最小zoomlevel
                zoomlevel = layer.minZoomLevel;
            }
            if (this.map.zoom > zoomlevel) { //如果当前地图窗口的zoomlevel更大就保留
                zoomlevel = this.map.zoom;
            }

            for each (var feaTmp:Feature in layer.features) {
                if (feaTmp.objectId == objectid) {
                    this.LocateFeature(feaTmp, zoomlevel, centered, appendmode, spec);
                    return;
                }
            }

            //如果当前map是逻辑图窗口，则推出。 逻辑图只在当前图上查询
            if (this.map.logicalMapId > 0) {
                return;
            }

            //如果是地图上的设施，继续到数据库里查询
            var oQuery:LayerObjectIdQuery = new LayerObjectIdQuery(layerid, objectid);
            oQuery.onResult = onQueryByObjectId;
            oQuery.execute();

            var needAlert:Boolean = spec.hasOwnProperty("needAlert") ? spec.needAlert == true : true;

            /**根据图层id和设施id 查询 矢量设施数据*/
            function onQueryByObjectId(layerData:LayerData, token:Object = null):void {
                if (!layerData || !layerData.features) {
                    if (needAlert) {
                        ErrorManager.showErrorMessage("地图上没有查询到设施图形");
                    }
                    return;
                }
                if (layerData.features.length == 0) {
                    if (needAlert) {
                        ErrorManager.showErrorMessage("地图上没有查询到设施图形");
                    }
                    return;
                }

                //加入feature到图层
                var nCount:int = layerData.features.length;
                if (nCount > 0) {
                    var fea:Feature = layerData.features.getItemAt(0) as Feature;
                    if (fea) {
                        layer.addFeature(fea);
                    }
                    LocateFeature(fea, zoomlevel, centered, appendmode, spec);
                }
            }

        }

        /**
         * 定位指定图层中的objectid数组
         * @param layerid 图层id
         * @param objectidList 对象的id数组
         * @param appendmode 是否追加模式，true:不清除掉原来的高亮设施
         * @param hilighted 是否一致闪烁
         */
        public function QueryAndLocateFeaturesByIds(layerid:Number, objectidList:ArrayCollection, centered:Boolean = true, appendmode:Boolean = false, hilighted:Boolean = true):void {
            var i:int = 0;
            var datalayer:FeatureLayer = map.getLayerById(layerid) as FeatureLayer;
            if (!datalayer) {
                trace("QueryAndLocateFeaturesByIds,没有取到layerData对应的图层");
                return;
            }

            if (!appendmode) {
                //清除已有高亮图层
                this.map.removeAllHiLightLayers();
            }

            if (null == objectidList) {
                return;
            }
            else {
                if (objectidList.length == 0) {
                    return;
                }
            }

            //到数据库里查询
            var oQuery:LayerObjectIdsQuery = new LayerObjectIdsQuery(layerid, objectidList);
            oQuery.onResult = onQueryByLayerAndObjectIds;
            oQuery.execute();

            /**根据图层id和objectids 查询 矢量设施数据*/
            function onQueryByLayerAndObjectIds(layerData:LayerData, token:Object = null):void {
                if (!layerData || !layerData.features) {
                    ErrorManager.showErrorMessage("地图上没有查询到设施图形");
                    return;
                }

                if (layerData.features.length == 0) {
                    ErrorManager.showErrorMessage("地图上没有查询到设施图形");
                    return;
                }

                var layer:FeatureLayer = map.getLayerById(layerData.layerId) as FeatureLayer;
                if (!layer) {
                    trace("QueryAndLocateFeaturesByIds,没有取到layerData对应的图层");
                    return;
                }

                //查看动态图层（id为真实图层的负值）是否存在,不存在新建一个
                var dynamicLayer:FeatureLayer = map.getLayerById(-layerid) as FeatureLayer;
                if (!dynamicLayer) {
                    dynamicLayer = datalayer.clone() as FeatureLayer;
                    dynamicLayer.id = -layerid;
                    dynamicLayer.layerType = LayerTypeEnum.DYNAMICLAYER;
                    dynamicLayer.levelable = false;
                    map.addLayer(dynamicLayer);
                }

                //加入feature到图层
                var nCount:int = layerData.features.length;
                /////
                var features:Vector.<Feature> = new Vector.<Feature>();
                var queryExtent:Extent = null;
                if (nCount > 0) {
                    for (i = 0; i < nCount; i++) {
                        var fea:Feature = layerData.features.getItemAt(i) as Feature;
                        ////
                        features.push(fea);

                        if (i == 0) {
                            queryExtent = fea.geometry.getExtent();
                        }
                        else {
                            queryExtent.encloseExtent(fea.geometry.getExtent());
                        }
                        dynamicLayer.addFeature(fea);
                        //fea.selected = true;
                        if (hilighted) {
                            //一直闪烁
                            new GlowTween(fea, 0, 0xffff00, 0, 5);
                        }
                        /*                  //发出选中设施事件
                           var fevt:FeatureEvent = new FeatureEvent(FeatureEvent.FEATURE_SELECTED, fea);
                         map.dispatchEvent(fevt);*/
                        var event:FeatureEvent = new FeatureEvent(FeatureEvent.FEATURE_LOCATE_END, null);
                        event.features = features;
                        map.dispatchEvent(event);
                    }

                    //缩放地图到extent
                    if (queryExtent && centered) {
                        map.zoomToExtent(queryExtent);
                    }

                }
            }
        }

        public function spatialQueryByGeometry():LayerData {
            return null;
        }

    }
}